import axios, { AxiosResponse, AxiosRequestConfig } from "axios";
import { useRouter } from "vue-router";
import { baseURL } from "../config/index";
import { ContentType } from "./enum";
import qs from "qs";
import store from "../store/index";
import { ElMessage } from "element-plus";
import { Response } from "./type";
const router = useRouter();
const logout = () => {
  store.dispatch("logout");
  router.replace("/login");
};
const instance = axios.create({
  baseURL: baseURL,
  timeout: 2500,
  headers: { "Content-Type": ContentType.JSON },
});
// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    if (config.headers && config.headers["Content-Type"] == ContentType.FORM) {
      config.data = qs.stringify(config.data);
    }
    //如果登录了
    if (store.state.isLogin && config.headers) {
      config.headers.token= store.state.token as string;
    }
    // 在发送请求之前做些什么
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response: AxiosResponse<string | Response>) {
    // 对响应数据做点什么
    if (response.data) {
      if (typeof response.data == "string") {
        response.data = JSON.parse(response.data);
        console.log("response.data", response.data);
      }
      if ((response.data as Response).code != 0) {
        //token失效
        if (
          (response.data as Response).code == -10009 ||
          (response.data as Response).code == -10010
        ) {
          logout();
          return;
        }
        ElMessage.error((response.data as Response).message);
        return Promise.reject(response);
      }
    }
    return response;
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export default instance;
